<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { 
  Box, 
  Money, 
  Star, 
  CircleCheck, 
  Calendar, 
  Wallet, 
  Position, 
  Refresh, 
  Shop, 
  User, 
  Location,
  Place,
  Timer
} from '@element-plus/icons-vue';
import RiderLayout from '@/components/rider/RiderLayout.vue';
import DeliveryMap from '@/components/rider/DeliveryMap.vue';
import { riderApi } from '@/api/rider';
import type { WorkStatus } from '@/types/rider';

// 订单类型定义
interface OrderItem {
  id: number;
  orderNumber: string;
  restaurant: string;
  customer: string;
  address: string;
  amount: number;
  distance: string;
  estimatedTime: string;
  pickupAddress?: string;
  items?: string[];
  createdAt?: Date;
  status?: string;
  pickupTime?: string;
  estimatedDeliveryTime?: string;
  delivery_coordinates?: string;
  delivery_address?: string;
  customer_phone?: string;
  // 新增字段
  deliveryFee?: number;
  storeAddress?: string;
  storeImage?: string;
  pickup_coordinates?: string;
}

const router = useRouter();

// 骑手统计数据
const riderStats = reactive({
  todayOrders: 0,
  todayEarnings: 0,
  monthlyOrders: 0,
  monthlyEarnings: 0,
  rating: 0,
  onlineTime: '0小时0分钟',
  completionRate: 0
});

// 待接订单列表
const pendingOrders = ref<OrderItem[]>([]);

// 已接订单列表  
const acceptedOrders = ref<OrderItem[]>([]);

// 加载状态
const loading = reactive({
  stats: false,
  orders: false,
  accepting: false
});

// 展开状态
const showAllPendingOrders = ref(false);
const showAllAcceptedOrders = ref(false);

// 地图相关状态
const mapVisible = ref(false);
const selectedOrder = ref<OrderItem | null>(null);
const riderLocation = ref({
  latitude: 39.9042,   // 默认位置
  longitude: 116.4074
});
const locationLoading = ref(false);

// 订单详情弹框状态
const orderDetailVisible = ref(false);
const orderDetailData = ref<OrderItem | null>(null);

// 地址转坐标缓存
const addressCache = new Map<string, string>();

// 获取骑手真实位置
const getRiderLocation = async () => {
  locationLoading.value = true;
  
  try {
    if (!navigator.geolocation) {
      ElMessage.warning('浏览器不支持定位功能，使用默认位置');
      return;
    }

    const position = await new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(
        resolve,
        reject,
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 60000
        }
      );
    });

    riderLocation.value = {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    };

    ElMessage.success('位置获取成功');
    console.log('骑手真实位置:', riderLocation.value);
    
  } catch (error) {
    console.error('获取位置失败:', error);
    
    if (error instanceof GeolocationPositionError) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          ElMessage.error('定位权限被拒绝，请在浏览器设置中允许位置访问');
          break;
        case error.POSITION_UNAVAILABLE:
          ElMessage.warning('位置信息不可用，使用默认位置');
          break;
        case error.TIMEOUT:
          ElMessage.warning('定位超时，使用默认位置');
          break;
        default:
          ElMessage.warning('定位失败，使用默认位置');
      }
    } else {
      ElMessage.warning('定位失败，使用默认位置');
    }
  } finally {
    locationLoading.value = false;
  }
};

// 高德地图API配置
const AMAP_KEY = '52dd86f4793513b166a46cb375010201'; // 需要替换为真实的API Key

// 切换待接订单显示数量
const togglePendingOrders = () => {
  showAllPendingOrders.value = !showAllPendingOrders.value;
};

// 切换进行中订单显示数量  
const toggleAcceptedOrders = () => {
  showAllAcceptedOrders.value = !showAllAcceptedOrders.value;
};

// 显示配送地图
const showDeliveryMap = async (order: OrderItem) => {
  const loadingInstance = ElMessage({
    message: '正在获取位置信息...',
    type: 'info',
    duration: 0
  });
  
  try {
    let deliveryCoordinates: string | null = order.delivery_coordinates || null;
    let pickupCoordinates: string | null = order.pickup_coordinates || null;
    
    // 如果没有配送地坐标，先转换地址为坐标
    if (!deliveryCoordinates && order.address) {
      deliveryCoordinates = await geocodeAddress(order.address);
    }
    
    // 如果没有取餐地坐标，转换商家地址为坐标
    if (!pickupCoordinates && (order.pickupAddress || order.storeAddress)) {
      const pickupAddress = order.pickupAddress || order.storeAddress || '';
      pickupCoordinates = await geocodeAddress(pickupAddress);
    }
    
    // 如果API调用失败，使用默认坐标
    if (!deliveryCoordinates) {
      deliveryCoordinates = generateDefaultCoordinates(order.address || '');
      console.log('使用默认配送坐标:', deliveryCoordinates);
    } else {
      console.log('配送地址转坐标成功:', order.address, '->', deliveryCoordinates);
    }

    if (!pickupCoordinates) {
      const pickupAddress = order.pickupAddress || order.storeAddress || '';
      pickupCoordinates = generateDefaultCoordinates(pickupAddress, true);
      console.log('使用默认取餐坐标:', pickupCoordinates);
    } else {
      console.log('取餐地址转坐标成功:', order.pickupAddress || order.storeAddress, '->', pickupCoordinates);
    }
    
    // 更新订单的坐标信息
    const updatedOrder: OrderItem = {
      ...order,
      delivery_coordinates: deliveryCoordinates,
      pickup_coordinates: pickupCoordinates,
      delivery_address: order.address,
      customer_phone: order.customer_phone || '暂无电话'
    };
    
    selectedOrder.value = updatedOrder;
    mapVisible.value = true;
    
  } catch (error) {
    console.error('获取位置信息失败:', error);
    ElMessage.error('获取位置信息失败');
  } finally {
    loadingInstance.close();
  }
};

// 关闭地图
const closeDeliveryMap = () => {
  mapVisible.value = false;
  selectedOrder.value = null;
};

// 显示订单详情
const showOrderDetail = (order: OrderItem) => {
  orderDetailData.value = order;
  orderDetailVisible.value = true;
};

// 关闭订单详情
const closeOrderDetail = () => {
  orderDetailVisible.value = false;
  orderDetailData.value = null;
};

// 处理位置更新
const handleLocationUpdate = (location: { latitude: number; longitude: number }) => {
  riderLocation.value = location;
  console.log('骑手位置已更新:', location);
};

// 使用高德地图API将地址转换为坐标
const geocodeAddress = async (address: string): Promise<string | null> => {
  // 检查缓存
  if (addressCache.has(address)) {
    return addressCache.get(address)!;
  }

  try {
    const response = await fetch(
      `https://restapi.amap.com/v3/geocode/geo?key=${AMAP_KEY}&address=${encodeURIComponent(address)}`
    );
    
    const data = await response.json();
    
    if (data.status === '1' && data.geocodes && data.geocodes.length > 0) {
      const location = data.geocodes[0].location; // 格式: "116.397128,39.916527"
      const [lng, lat] = location.split(',');
      const coordinates = `${lat},${lng}`; // 转换为 latitude,longitude 格式
      
      // 缓存结果
      addressCache.set(address, coordinates);
      return coordinates;
    } else {
      console.warn('地址转坐标失败:', address, data);
      return null;
    }
  } catch (error) {
    console.error('地址转坐标API调用失败:', error);
    return null;
  }
};

// 生成默认坐标（北京理工大学附近的随机位置）
const generateDefaultCoordinates = (address: string, isPickup = false): string => {
  // 基于地址生成相对稳定的随机坐标
  const hash = address.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  
  // 北京理工大学附近的坐标
  let baseLat = 39.9042;
  let baseLng = 116.4074;
  
  // 如果是取餐地址，使用校内美食街坐标
  if (isPickup) {
    baseLat = 39.9038;
    baseLng = 116.4068;
  }
  
  const offset = 0.01; // 约1km范围
  
  const latOffset = (Math.abs(hash) % 1000) / 1000 * offset - offset / 2;
  const lngOffset = (Math.abs(hash >> 10) % 1000) / 1000 * offset - offset / 2;
  
  const lat = baseLat + latOffset;
  const lng = baseLng + lngOffset;
  
  return `${lat.toFixed(6)},${lng.toFixed(6)}`;
};

// 刷新定时器
let refreshTimer: number | null = null;

// 获取统计数据
const getStatsData = async () => {
  loading.stats = true;
  try {
    // 获取今日统计
    const todayResponse = await riderApi.getStats('day');
    if (todayResponse.data.data) {
      // 映射API返回的字段到前端数据结构
      riderStats.todayOrders = todayResponse.data.data.ordersCount || todayResponse.data.data.orders || 0;
      riderStats.todayEarnings = todayResponse.data.data.totalIncome || todayResponse.data.data.earnings || 0;
      riderStats.completionRate = todayResponse.data.data.completionRate || 0;
    }

    // 获取月度统计
    const monthlyResponse = await riderApi.getStats('month');
    if (monthlyResponse.data.data) {
      riderStats.monthlyOrders = monthlyResponse.data.data.ordersCount || monthlyResponse.data.data.orders || 0;
      riderStats.monthlyEarnings = monthlyResponse.data.data.totalIncome || monthlyResponse.data.data.earnings || 0;
    }

    // 获取骑手评分（模拟数据，实际应该从用户信息接口获取）
    riderStats.rating = 4.8;
    
    // 计算今日在线时长（模拟数据）
    const startTime = new Date();
    startTime.setHours(8, 0, 0); // 假设8点上班
    const currentTime = new Date();
    const onlineMinutes = Math.floor((currentTime.getTime() - startTime.getTime()) / (1000 * 60));
    const hours = Math.floor(onlineMinutes / 60);
    const minutes = onlineMinutes % 60;
    riderStats.onlineTime = `${hours}小时${minutes}分钟`;
    
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取统计数据失败');
  } finally {
    loading.stats = false;
  }
};

// 获取可接订单列表
const getAvailableOrders = async () => {
  loading.orders = true;
  try {
    const response = await riderApi.getAvailableOrders();
    if (response.data && response.data.data) {
      const rawOrders = response.data.data.map((order: any) => ({
        id: order.id,
        orderNumber: order.orderNo || order.orderNumber,
        restaurant: order.storeName || order.restaurant?.name || '未知商家',
        customer: order.userName || order.customer?.name || '顾客',
        address: order.userAddress || order.deliveryAddress,
        amount: order.paymentAmount || order.totalAmount || 0,
        distance: order.distance ? `${order.distance}公里` : '计算中',
        estimatedTime: order.estimatedDeliveryTime ? `${order.estimatedDeliveryTime}分钟` : '计算中',
        pickupAddress: order.storeAddress || order.restaurant?.address || '取餐地址',
        items: order.items || [],
        createdAt: order.createdAt,
        deliveryFee: order.deliveryFee || 0,
        storeAddress: order.storeAddress,
        storeImage: order.storeImage,
        // 保存原始坐标
        delivery_coordinates: order.coordinates || order.deliveryCoordinates,
        pickup_coordinates: order.pickupCoordinates || order.storeCoordinates
      }));
      
      pendingOrders.value = rawOrders;
      
      // 异步计算距离
      calculateOrderDistances(rawOrders);
    }
  } catch (error) {
    console.error('获取待接订单失败:', error);
    // 使用模拟数据作为fallback
    pendingOrders.value = [
      {
        id: 1,
        orderNumber: 'BLM202412260001',
        restaurant: '兰州拉面',
        customer: '张先生',
        address: '北京理工大学宿舍区6号楼',
        amount: 38.5,
        distance: '1.2公里',
        estimatedTime: '25分钟',
        pickupAddress: '北京理工大学美食街A区',
        items: ['兰州拉面', '小菜'],
        createdAt: new Date(),
        deliveryFee: 5.0,
        storeAddress: '北京理工大学美食街A区兰州拉面店',
        storeImage: ''
      },
      {
        id: 2,
        orderNumber: 'BLM202412260002',
        restaurant: '麻辣烫小屋',
        customer: '李女士',
        address: '北京理工大学图书馆',
        amount: 24.0,
        distance: '0.8公里',
        estimatedTime: '20分钟',
        pickupAddress: '北京理工大学美食街B区',
        items: ['麻辣烫', '饮料'],
        createdAt: new Date(),
        deliveryFee: 4.0,
        storeAddress: '北京理工大学美食街B区麻辣烫小屋',
        storeImage: ''
      }
    ];
  } finally {
    loading.orders = false;
  }
};

// 获取已接订单列表
const getAcceptedOrders = async () => {
  try {
    const response = await riderApi.getAcceptedOrders();
    if (response.data && response.data.data) {
      const rawOrders = response.data.data.map((order: any) => ({
        id: order.id,
        orderNumber: order.orderNo || order.orderNumber,
        restaurant: order.storeName || order.restaurant?.name || '未知商家',
        customer: order.userName || order.customer?.name || '顾客',
        address: order.userAddress || order.deliveryAddress,
        amount: order.paymentAmount || order.totalAmount || 0,
        status: order.orderStatus || order.status,
        pickupTime: order.pickupTime,
        estimatedDeliveryTime: order.estimatedDeliveryTime,
        createdAt: order.createdAt,
        distance: order.distance ? `${order.distance}公里` : '计算中',
        estimatedTime: order.estimatedTime ? `${order.estimatedTime}分钟` : '计算中',
        // 保留原有坐标（如果有的话）
        delivery_coordinates: order.coordinates || order.deliveryCoordinates,
        delivery_address: order.userAddress || order.deliveryAddress,
        customer_phone: order.userPhone || order.customerPhone,
        // 新增字段
        deliveryFee: order.deliveryFee || 0,
        storeAddress: order.storeAddress,
        storeImage: order.storeImage,
        pickupAddress: order.storeAddress || order.restaurant?.address || '取餐地址'
      }));
      
      // 对订单进行排序：优先级 + 时间
      acceptedOrders.value = sortAcceptedOrders(rawOrders);
    }
  } catch (error) {
    console.error('获取已接订单失败:', error);
    // 使用模拟数据用于测试地图功能
    const mockAcceptedOrders = [
      {
        id: 101,
        orderNumber: 'BLM202412260101',
        restaurant: '北理工食堂',
        customer: '王同学',
        address: '北京理工大学7号宿舍楼201',
        amount: 28.5,
        distance: '0.8公里',
        estimatedTime: '15分钟',
        status: 'RIDER_ASSIGNED',
        pickupTime: '12:30',
        estimatedDeliveryTime: '13:00',
        createdAt: new Date(),
        delivery_coordinates: '39.9042,116.4074',
        delivery_address: '北京理工大学7号宿舍楼201',
        customer_phone: '138****5678',
        deliveryFee: 3.0,
        storeAddress: '北京理工大学第一食堂',
        pickupAddress: '北京理工大学第一食堂',
        pickup_coordinates: '39.9045,116.4070'
      },
      {
        id: 102,
        orderNumber: 'BLM202412260102',
        restaurant: '麻辣香锅',
        customer: '李同学',
        address: '北京理工大学图书馆附近',
        amount: 45.0,
        distance: '1.2公里',
        estimatedTime: '20分钟',
        status: 'FOOD_PICKED',
        pickupTime: '12:45',
        estimatedDeliveryTime: '13:15',
        createdAt: new Date(),
        delivery_coordinates: '39.9056,116.4089',
        delivery_address: '北京理工大学图书馆附近',
        customer_phone: '139****1234',
        deliveryFee: 5.0,
        storeAddress: '北京理工大学美食街麻辣香锅店',
        pickupAddress: '北京理工大学美食街麻辣香锅店',
        pickup_coordinates: '39.9040,116.4065'
      }
    ];
    acceptedOrders.value = sortAcceptedOrders(mockAcceptedOrders);
  }
};

// 接单
const acceptOrder = async (orderId: number) => {
  loading.accepting = true;
  try {
    await riderApi.acceptOrder(orderId.toString());
    ElMessage.success('接单成功！');
    
    // 刷新订单列表
    await Promise.all([
      getAvailableOrders(),
      getAcceptedOrders()
    ]);
    
  } catch (error) {
    console.error('接单失败:', error);
    ElMessage.error('接单失败，请重试');
  } finally {
    loading.accepting = false;
  }
};

// 取餐
const pickupOrder = async (orderId: number) => {
  try {
    await riderApi.pickupOrder(orderId.toString());
    ElMessage.success('取餐成功，开始配送！');
    
    // 刷新已接订单列表并重新排序
    await getAcceptedOrders();
  } catch (error) {
    console.error('取餐失败:', error);
    ElMessage.error('取餐失败，请重试');
  }
};

// 送达订单
const deliverOrder = async (orderId: number) => {
  try {
    await riderApi.deliverOrder(orderId.toString());
    ElMessage.success('订单已送达！');
    
    // 刷新数据并重新排序
    await Promise.all([
      getStatsData(),
      getAcceptedOrders()
    ]);
  } catch (error) {
    console.error('送达失败:', error);
    ElMessage.error('送达失败，请重试');
  }
};

// 刷新所有数据
const refreshData = async () => {
  await Promise.all([
    getStatsData(),
    getAvailableOrders(),
    getAcceptedOrders()
  ]);
};

// 开始自动刷新
const startAutoRefresh = () => {
  // 每30秒刷新一次订单数据
  refreshTimer = window.setInterval(() => {
    getAvailableOrders();
    getAcceptedOrders();
  }, 30000);
  
  // 每5分钟刷新一次统计数据
  setInterval(() => {
    getStatsData();
  }, 5 * 60 * 1000);
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

// 格式化时间
const formatTime = (date: string | Date) => {
  const d = new Date(date);
  return d.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

// 格式化金额
const formatAmount = (amount: number) => {
  return `¥${amount.toFixed(2)}`;
};

// 智能计算预计时间（根据订单状态）
const calculateSmartEstimatedTime = (order: OrderItem) => {
  const status = order.status;
  
  // 判断是否已取餐
  const isPickedUp = ['FOOD_PICKED', 'PICKED_UP', 'DELIVERING'].includes(status || '');
  
  if (isPickedUp) {
    // 已取餐：只计算到顾客的时间
    const directDistance = calculateOrderDistance(order, true);
    const timeToCustomer = Math.ceil(directDistance * 2.5); // 每公里2.5分钟
    return `${timeToCustomer}分钟`;
  } else {
    // 未取餐：计算到商家+到顾客的总时间
    const fullDistance = calculateOrderDistance(order, false);
    const totalTime = Math.ceil(fullDistance * 3) + 5; // 每公里3分钟 + 5分钟取餐时间
    return `${totalTime}分钟`;
  }
};

// 异步计算订单距离列表
const calculateOrderDistances = async (orders: OrderItem[]) => {
  try {
    for (const order of orders) {
      // 如果已经有距离信息，跳过
      if (order.distance !== '计算中') {
        continue;
      }
      
      let calculatedDistance = '计算中';
      
      try {
        // 方法1：如果有坐标，直接计算
        if (order.delivery_coordinates && order.pickup_coordinates) {
          const distance = calculateFullRouteDistance(order);
          calculatedDistance = `${distance.toFixed(1)}公里`;
        }
        // 方法2：如果有地址，先转换为坐标再计算
        else if (order.address && (order.pickupAddress || order.storeAddress)) {
          const [deliveryCoords, pickupCoords] = await Promise.all([
            geocodeAddress(order.address),
            geocodeAddress(order.pickupAddress || order.storeAddress || '')
          ]);
          
          if (deliveryCoords && pickupCoords) {
            const tempOrder = {
              ...order,
              delivery_coordinates: deliveryCoords,
              pickup_coordinates: pickupCoords
            };
            const distance = calculateFullRouteDistance(tempOrder);
            calculatedDistance = `${distance.toFixed(1)}公里`;
          }
        }
        // 方法3：使用估算距离
        else {
          const estimatedDistance = 2 + Math.random() * 3; // 2-5公里的估算
          calculatedDistance = `约${estimatedDistance.toFixed(1)}公里`;
        }
      } catch (error) {
        console.error(`计算订单${order.id}距离失败:`, error);
        // 使用估算距离作为备选
        const estimatedDistance = 2 + Math.random() * 3;
        calculatedDistance = `约${estimatedDistance.toFixed(1)}公里`;
      }
      
      // 更新订单列表中的距离信息
      const orderIndex = pendingOrders.value.findIndex(o => o.id === order.id);
      if (orderIndex !== -1) {
        pendingOrders.value[orderIndex].distance = calculatedDistance;
      }
      
      // 避免过于频繁的API调用
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  } catch (error) {
    console.error('批量计算订单距离失败:', error);
  }
};

// 计算订单距离（简化版本）
const calculateOrderDistance = (order: OrderItem, directToCustomer: boolean) => {
  // 如果有真实坐标，使用真实距离计算
  if (order.delivery_coordinates && order.pickup_coordinates && !directToCustomer) {
    // 计算完整路径：骑手→商家→顾客
    return calculateFullRouteDistance(order);
  } else if (order.delivery_coordinates && directToCustomer) {
    // 计算直接路径：骑手→顾客
    return calculateDirectRouteDistance(order);
  }
  
  // 降级到估算距离
  return Math.random() * 5 + 1; // 1-6公里的随机值
};

// 计算完整路径距离
const calculateFullRouteDistance = (order: OrderItem) => {
  try {
    const [pickupLat, pickupLng] = order.pickup_coordinates!.split(',').map(Number);
    const [destLat, destLng] = order.delivery_coordinates!.split(',').map(Number);
    
    // 骑手→商家距离
    const distanceToPickup = calculateHaversineDistance(
      riderLocation.value.latitude,
      riderLocation.value.longitude,
      pickupLat,
      pickupLng
    );
    
    // 商家→顾客距离
    const distanceToCustomer = calculateHaversineDistance(
      pickupLat,
      pickupLng,
      destLat,
      destLng
    );
    
    return distanceToPickup + distanceToCustomer;
  } catch (error) {
    console.error('完整路径距离计算失败:', error);
    return Math.random() * 5 + 1;
  }
};

// 计算直接路径距离
const calculateDirectRouteDistance = (order: OrderItem) => {
  try {
    const [destLat, destLng] = order.delivery_coordinates!.split(',').map(Number);
    
    // 骑手→顾客距离
    return calculateHaversineDistance(
      riderLocation.value.latitude,
      riderLocation.value.longitude,
      destLat,
      destLng
    );
  } catch (error) {
    console.error('直接路径距离计算失败:', error);
    return Math.random() * 3 + 1;
  }
};

// Haversine距离公式
const calculateHaversineDistance = (lat1: number, lng1: number, lat2: number, lng2: number) => {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
            Math.cos(lat1 * Math.PI / 180) * 
            Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLng/2) * Math.sin(dLng/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  return R * c;
};

// 获取订单状态文本
const getStatusText = (status?: string) => {
  const statusMap: Record<string, string> = {
    'ORDER_CREATED': '待支付',
    'PENDING': '等待商家接单', 
    'MERCHANT_CONFIRMED': '商家已接单',
    'READY_WAITING_RIDER': '等待骑手取餐',
    'RIDER_ASSIGNED': '骑手已接单',
    'FOOD_PICKED': '配送中',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
    // 兼容旧的状态值
    'ACCEPTED': '骑手已接单',
    'PICKED_UP': '配送中',
    'DELIVERING': '配送中'
  };
  return statusMap[status || ''] || '未知状态';
};

// 判断订单是否可以接单
const canAcceptOrder = (status?: string) => {
  return status === 'READY_WAITING_RIDER';
};

// 判断订单是否可以取餐
const canPickupOrder = (status?: string) => {
  return status === 'RIDER_ASSIGNED' || status === 'ACCEPTED';
};

// 判断订单是否可以送达
const canDeliverOrder = (status?: string) => {
  return status === 'FOOD_PICKED' || status === 'PICKED_UP';
};

// 获取订单状态对应的CSS类名
const getStatusClass = (status?: string) => {
  return status || 'unknown';
};

// 获取订单状态优先级（数字越小优先级越高）
const getStatusPriority = (status?: string) => {
  const priorityMap: Record<string, number> = {
    'FOOD_PICKED': 1,        // 已取餐（配送中）- 最高优先级
    'RIDER_ASSIGNED': 2,     // 已接单 - 第二优先级
    'ACCEPTED': 2,           // 兼容旧状态
    'DELIVERED': 3,          // 已送达 - 最低优先级
    'COMPLETED': 4,          // 已完成
    'PICKED_UP': 1,          // 兼容旧状态
    'DELIVERING': 1          // 兼容旧状态
  };
  return priorityMap[status || ''] || 999;
};

// 对进行中订单进行排序
const sortAcceptedOrders = (orders: OrderItem[]) => {
  return [...orders].sort((a, b) => {
    // 首先按状态优先级排序
    const priorityA = getStatusPriority(a.status);
    const priorityB = getStatusPriority(b.status);
    
    if (priorityA !== priorityB) {
      return priorityA - priorityB;
    }
    
    // 相同状态按时间从早到晚排序
    const timeA = new Date(a.createdAt || 0).getTime();
    const timeB = new Date(b.createdAt || 0).getTime();
    return timeA - timeB;
  });
};

onMounted(() => {
  console.log('骑手端首页加载完成');
  refreshData();
  startAutoRefresh();
  
  // 自动获取骑手位置
  getRiderLocation();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<template>
  <RiderLayout>
    <div class="dashboard-content">
      <!-- 统计卡片区域 -->
      <div class="stats-section">
        <h2 class="section-title">工作概览</h2>
        <el-row :gutter="20">
          <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
            <el-card shadow="hover" class="stat-card-wrapper">
              <div class="stat-card" v-loading="loading.stats">
                <div class="stat-icon orders">
                  <el-icon><Box /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-title">今日订单</div>
                  <div class="stat-value">{{ riderStats.todayOrders }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
            <el-card shadow="hover" class="stat-card-wrapper">
              <div class="stat-card" v-loading="loading.stats">
                <div class="stat-icon earnings">
                  <el-icon><Money /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-title">今日收益</div>
                  <div class="stat-value">{{ formatAmount(riderStats.todayEarnings) }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
            <el-card shadow="hover" class="stat-card-wrapper">
              <div class="stat-card" v-loading="loading.stats">
                <div class="stat-icon rating">
                  <el-icon><Star /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-title">服务评分</div>
                  <div class="stat-value">{{ riderStats.rating.toFixed(1) }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
            <el-card shadow="hover" class="stat-card-wrapper">
              <div class="stat-card" v-loading="loading.stats">
                <div class="stat-icon completion">
                  <el-icon><CircleCheck /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-title">完成率</div>
                  <div class="stat-value">{{ riderStats.completionRate }}%</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 位置信息区域 -->
      <div class="location-section">
        <h2 class="section-title">位置信息</h2>
        <el-card shadow="hover">
          <div class="location-info">
            <div class="location-display">
              <div class="location-icon">
                <el-icon><Location /></el-icon>
              </div>
              <div class="location-details">
                <div class="location-title">当前位置</div>
                <div class="location-coords">
                  纬度: {{ riderLocation.latitude.toFixed(6) }}, 经度: {{ riderLocation.longitude.toFixed(6) }}
                </div>
              </div>
            </div>
            <div class="location-actions">
              <el-button 
                type="primary" 
                @click="getRiderLocation" 
                :loading="locationLoading"
                :icon="Refresh"
              >
                {{ locationLoading ? '定位中...' : '刷新位置' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 月度统计 -->
      <el-row :gutter="20" class="dashboard-row">
        <el-col :span="24">
          <el-card shadow="hover" class="monthly-stats-card" v-loading="loading.stats">
            <template #header>
              <div class="card-header">
                <span>本月统计</span>
              </div>
            </template>
            <div class="monthly-stats-content">
              <div class="monthly-item">
                <div class="monthly-icon monthly">
                  <el-icon><Calendar /></el-icon>
                </div>
                <div class="monthly-info">
                  <div class="monthly-label">月度订单</div>
                  <div class="monthly-value">{{ riderStats.monthlyOrders }}单</div>
                </div>
              </div>
              <div class="monthly-item">
                <div class="monthly-icon earning">
                  <el-icon><Wallet /></el-icon>
                </div>
                <div class="monthly-info">
                  <div class="monthly-label">月度收益</div>
                  <div class="monthly-value">{{ formatAmount(riderStats.monthlyEarnings) }}</div>
                </div>
              </div>
              <div class="monthly-item">
                <div class="monthly-icon online">
                  <el-icon><Timer /></el-icon>
                </div>
                <div class="monthly-info">
                  <div class="monthly-label">今日在线</div>
                  <div class="monthly-value">{{ riderStats.onlineTime }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 订单管理区域 -->
      <el-row :gutter="20" class="dashboard-row">
        <!-- 待接订单 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="hover" class="orders-card">
            <template #header>
              <div class="card-header">
                <span>待接订单</span>
                <el-button 
                  @click="getAvailableOrders" 
                  :loading="loading.orders"
                  type="primary" 
                  size="small"
                  text
                >
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            
            <div class="orders-content">
              <template v-if="loading.orders">
                <el-skeleton :rows="3" animated />
              </template>
              <template v-else-if="pendingOrders.length === 0">
                <div class="empty-container">
                  <el-empty description="暂无待接订单" :image-size="80" />
                </div>
              </template>
              <template v-else>
                <div class="orders-list">
                  <div 
                    v-for="order in showAllPendingOrders ? pendingOrders : pendingOrders.slice(0, 3)" 
                    :key="order.id" 
                    class="order-item"
                  >
                    <div class="order-header">
                      <div class="order-number">{{ order.orderNumber }}</div>
                      <div class="order-amount">{{ formatAmount(order.amount) }}</div>
                    </div>
                    
                    <div class="order-info">
                      <div class="info-row">
                        <el-icon><Shop /></el-icon>
                        <span>{{ order.restaurant }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Position /></el-icon>
                        <span class="pickup-address">取餐: {{ order.pickupAddress || '商家地址' }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><User /></el-icon>
                        <span>{{ order.customer }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Location /></el-icon>
                        <span class="delivery-address">送达: {{ order.address }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Money /></el-icon>
                        <span>配送费: ¥{{ (order.deliveryFee || 0).toFixed(2) }}</span>
                      </div>
                    </div>
                    
                    <div class="order-meta">
                      <span class="distance">距离: {{ order.distance }}</span>
                      <span class="time">预计: {{ calculateSmartEstimatedTime(order) }}</span>
                    </div>
                    
                    <div class="order-actions">
                      <el-button 
                        size="small" 
                        @click="acceptOrder(order.id)"
                        type="primary"
                        :loading="loading.accepting"
                      >
                        接单
                      </el-button>
                      <el-button 
                        size="small" 
                        @click="showOrderDetail(order)"
                        type="info"
                        text
                      >
                        详情
                      </el-button>
                    </div>
                  </div>
                </div>
                <div v-if="pendingOrders.length > 3" class="view-more">
                  <el-button text type="primary" @click="togglePendingOrders">
                    {{ showAllPendingOrders ? '收起' : `查看全部 ${pendingOrders.length} 个订单` }}
                  </el-button>
                </div>
              </template>
            </div>
          </el-card>
        </el-col>

        <!-- 进行中订单 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="hover" class="orders-card">
              <template #header>
                <div class="card-header">
                  <div class="header-left">
                    <span>进行中订单</span>
                    <div class="priority-legend">
                      <span class="legend-item">
                        <span class="legend-dot urgent"></span>
                        配送中
                      </span>
                      <span class="legend-item">
                        <span class="legend-dot normal"></span>
                        待取餐
                      </span>
                    </div>
                  </div>
                  <el-button 
                    v-if="acceptedOrders.length > 3"
                    text 
                    type="primary" 
                    @click="toggleAcceptedOrders"
                    size="small"
                  >
                    {{ showAllAcceptedOrders ? '收起' : `查看全部 ${acceptedOrders.length} 个` }}
                  </el-button>
                </div>
              </template>            <div class="orders-content">
              <template v-if="acceptedOrders.length === 0">
                <div class="empty-container">
                  <el-empty description="暂无进行中订单" :image-size="80" />
                </div>
              </template>
              <template v-else>
                <div class="active-orders-list">
                  <div 
                    v-for="order in showAllAcceptedOrders ? acceptedOrders : acceptedOrders.slice(0, 3)" 
                    :key="order.id" 
                    class="active-order-item"
                    :class="{ 
                      'priority-high': getStatusPriority(order.status) === 1,
                      'priority-medium': getStatusPriority(order.status) === 2,
                      'priority-low': getStatusPriority(order.status) >= 3
                    }"
                  >
                    <!-- 优先级指示器 -->
                    <div class="priority-indicator" v-if="getStatusPriority(order.status) <= 2">
                      <div class="priority-dot" :class="{
                        'urgent': getStatusPriority(order.status) === 1,
                        'normal': getStatusPriority(order.status) === 2
                      }"></div>
                    </div>
                    
                    <div class="order-header">
                      <div class="order-number">{{ order.orderNumber }}</div>
                      <div class="order-status" :class="getStatusClass(order.status)">
                        {{ getStatusText(order.status) }}
                      </div>
                    </div>
                    
                    <div class="order-info">
                      <div class="info-row">
                        <el-icon><Shop /></el-icon>
                        <span>{{ order.restaurant }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Position /></el-icon>
                        <span class="pickup-address">取餐: {{ order.pickupAddress || order.storeAddress || '商家地址' }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Location /></el-icon>
                        <span class="delivery-address">送达: {{ order.address }}</span>
                      </div>
                      <div class="info-row">
                        <el-icon><Money /></el-icon>
                        <span>配送费: ¥{{ (order.deliveryFee || 0).toFixed(2) }} | 订单时间: {{ formatTime(order.createdAt || new Date()) }}</span>
                      </div>
                    </div>
                    
                    <div class="order-actions">
                      <!-- 详情按钮 -->
                      <el-button 
                        type="info" 
                        size="small"
                        @click="showOrderDetail(order)"
                        text
                      >
                        详情
                      </el-button>
                      <!-- 查看位置按钮 -->
                      <el-button 
                        v-if="order.status === 'RIDER_ASSIGNED' || order.status === 'FOOD_PICKED'"
                        type="info" 
                        size="small"
                        @click="showDeliveryMap(order)"
                        :icon="Place"
                      >
                        查看位置
                      </el-button>
                      <!-- 骑手已接单状态：显示取餐按钮 -->
                      <el-button 
                        v-if="canPickupOrder(order.status)" 
                        type="warning" 
                        size="small"
                        @click="pickupOrder(order.id)"
                      >
                        确认取餐
                      </el-button>
                      <!-- 骑手已取餐状态：显示送达按钮 -->
                      <el-button 
                        v-if="canDeliverOrder(order.status)" 
                        type="success" 
                        size="small"
                        @click="deliverOrder(order.id)"
                      >
                        确认送达
                      </el-button>
                      <!-- 已送达或已完成状态：无操作按钮 -->
                      <div 
                        v-if="order.status === 'DELIVERED' || order.status === 'COMPLETED'"
                        class="order-status-text"
                      >
                        订单{{ getStatusText(order.status) }}
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 配送地图组件 -->
    <DeliveryMap 
      :visible="mapVisible"
      :order="selectedOrder"
      :rider-location="riderLocation"
      @close="closeDeliveryMap"
      @location-update="handleLocationUpdate"
    />

    <!-- 订单详情弹框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="90%"
      :style="{ maxWidth: '500px' }"
      @close="closeOrderDetail"
    >
      <div v-if="orderDetailData" class="order-detail-content">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-row">
            <span class="label">订单号:</span>
            <span class="value">{{ orderDetailData.orderNumber }}</span>
          </div>
          <div class="detail-row">
            <span class="label">订单金额:</span>
            <span class="value amount">{{ formatAmount(orderDetailData.amount) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">配送费:</span>
            <span class="value">{{ formatAmount(orderDetailData.deliveryFee || 0) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">下单时间:</span>
            <span class="value">{{ new Date(orderDetailData.createdAt || new Date()).toLocaleString('zh-CN') }}</span>
          </div>
          <div class="detail-row" v-if="orderDetailData.status">
            <span class="label">订单状态:</span>
            <span class="value status" :class="getStatusClass(orderDetailData.status)">
              {{ getStatusText(orderDetailData.status) }}
            </span>
          </div>
        </div>

        <!-- 商家信息 -->
        <div class="detail-section">
          <h4>商家信息</h4>
          <div class="detail-row">
            <span class="label">商家名称:</span>
            <span class="value">{{ orderDetailData.restaurant }}</span>
          </div>
          <div class="detail-row">
            <span class="label">取餐地址:</span>
            <span class="value address">{{ orderDetailData.pickupAddress || orderDetailData.storeAddress || '暂无' }}</span>
          </div>
        </div>

        <!-- 顾客信息 -->
        <div class="detail-section">
          <h4>顾客信息</h4>
          <div class="detail-row">
            <span class="label">顾客姓名:</span>
            <span class="value">{{ orderDetailData.customer }}</span>
          </div>
          <div class="detail-row">
            <span class="label">配送地址:</span>
            <span class="value address">{{ orderDetailData.address }}</span>
          </div>
          <div class="detail-row" v-if="orderDetailData.customer_phone">
            <span class="label">联系电话:</span>
            <span class="value">{{ orderDetailData.customer_phone }}</span>
          </div>
        </div>

        <!-- 配送信息 -->
        <div class="detail-section" v-if="orderDetailData.status">
          <h4>配送信息</h4>
          <div class="detail-row">
            <span class="label">配送距离:</span>
            <span class="value">{{ orderDetailData.distance }}</span>
          </div>
          <div class="detail-row">
            <span class="label">预计时间:</span>
            <span class="value">{{ orderDetailData.estimatedTime }}</span>
          </div>
          <div class="detail-row" v-if="orderDetailData.pickupTime">
            <span class="label">取餐时间:</span>
            <span class="value">{{ orderDetailData.pickupTime }}</span>
          </div>
          <div class="detail-row" v-if="orderDetailData.estimatedDeliveryTime">
            <span class="label">预计送达:</span>
            <span class="value">{{ orderDetailData.estimatedDeliveryTime }}</span>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="detail-section" v-if="orderDetailData.items && orderDetailData.items.length > 0">
          <h4>商品信息</h4>
          <div class="items-list">
            <div v-for="(item, index) in orderDetailData.items" :key="index" class="item-row">
              <span>{{ item }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeOrderDetail">关闭</el-button>
          <el-button 
            v-if="orderDetailData && (orderDetailData.status === 'RIDER_ASSIGNED' || orderDetailData.status === 'FOOD_PICKED')"
            type="primary" 
            @click="showDeliveryMap(orderDetailData); closeOrderDetail();"
          >
            查看位置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </RiderLayout>
</template>

<style scoped>
.dashboard-content {
  padding: 20px 0;
  background-color: #f5f7fa;
}

.dashboard-row {
  margin-top: 20px;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 2px;
}

.stat-card-wrapper {
  height: 120px;
  overflow: hidden;
}

.stat-card {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.stat-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 64px;
  height: 64px;
  border-radius: 16px;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.earnings {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.rating {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.completion {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  line-height: 1;
}

/* 月度统计卡片 */
.monthly-stats-card {
  width: 100%;
}

.monthly-stats-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 16px 0;
}

.monthly-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.monthly-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.monthly-icon.monthly {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.monthly-icon.earning {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.monthly-icon.online {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.monthly-info {
  display: flex;
  flex-direction: column;
}

.monthly-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.monthly-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 位置信息区域 */
.location-section {
  margin-bottom: 20px;
}

.location-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.location-display {
  display: flex;
  align-items: center;
  gap: 16px;
}

.location-icon {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.location-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.location-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.location-coords {
  font-size: 12px;
  color: #666;
  font-family: 'Courier New', monospace;
}

.location-actions .el-button {
  min-width: 100px;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 优先级图例 */
.priority-legend {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #666;
  font-weight: normal;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.legend-dot.urgent {
  background: #f56c6c;
}

.legend-dot.normal {
  background: #e6a23c;
}

/* 订单卡片 */
.orders-card {
  height: 100%;
  min-height: 500px;
}

.orders-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  flex: 1;
}

.orders-list {
  flex: 1;
  max-height: calc(100vh - 400px);
  overflow-y: auto;
  padding-right: 4px;
}

/* 滚动条美化 */
.orders-list::-webkit-scrollbar {
  width: 6px;
}

.orders-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.orders-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.orders-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.order-item {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 10px;
  background: #fff;
  transition: all 0.3s ease;
}

.order-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.order-item:last-child {
  margin-bottom: 0;
}

.active-order-item {
  padding: 16px;
  border: 1px solid #e6f7ff;
  border-left: 4px solid #409eff;
  border-radius: 8px;
  margin-bottom: 10px;
  background: #fafcff;
  transition: all 0.3s ease;
  position: relative;
}

/* 优先级样式 */
.active-order-item.priority-high {
  border-left-color: #f56c6c;
  background: #fef0f0;
  border-color: #fde2e2;
}

.active-order-item.priority-medium {
  border-left-color: #e6a23c;
  background: #fdf6ec;
  border-color: #f5dab1;
}

.active-order-item.priority-low {
  border-left-color: #67c23a;
  background: #f0f9ff;
  border-color: #e1f3d8;
}

/* 优先级指示器 */
.priority-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
}

.priority-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.priority-dot.urgent {
  background: #f56c6c;
  box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7);
}

.priority-dot.normal {
  background: #e6a23c;
  box-shadow: 0 0 0 0 rgba(230, 162, 60, 0.7);
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.active-order-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.active-order-item:last-child {
  margin-bottom: 0;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.order-amount {
  font-size: 16px;
  font-weight: 700;
  color: #f56c6c;
}

.order-status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  background: #409eff;
  color: white;
}

/* 不同状态的颜色 */
.order-status.ORDER_CREATED {
  background: #f56c6c;
  color: white;
}

.order-status.PENDING {
  background: #e6a23c;
  color: white;
}

.order-status.MERCHANT_CONFIRMED {
  background: #409eff;
  color: white;
}

.order-status.READY_WAITING_RIDER {
  background: #e6a23c;
  color: white;
}

.order-status.RIDER_ASSIGNED {
  background: #409eff;
  color: white;
}

.order-status.FOOD_PICKED {
  background: #67c23a;
  color: white;
}

.order-status.DELIVERED {
  background: #67c23a;
  color: white;
}

.order-status.COMPLETED {
  background: #909399;
  color: white;
}

.order-status.CANCELLED {
  background: #f56c6c;
  color: white;
}

/* 兼容旧状态 */
.order-status.ACCEPTED {
  background: #409eff;
  color: white;
}

.order-status.PICKED_UP {
  background: #67c23a;
  color: white;
}

.order-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 14px;
  color: #666;
}

.info-row .el-icon {
  color: #409eff;
  font-size: 16px;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 13px;
  color: #999;
}

.order-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  align-items: center;
}

.order-status-text {
  font-size: 14px;
  color: #67c23a;
  font-weight: 500;
  text-align: center;
}

.view-more {
  text-align: center;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .monthly-stats-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .monthly-item {
    width: 100%;
    justify-content: center;
  }
  
  .orders-card {
    min-height: 450px;
  }
  
  .orders-list {
    max-height: calc(100vh - 450px);
  }
}

/* 平板端适配 */
@media (max-width: 992px) {
  .dashboard-content {
    padding: 16px;
  }
  
  .dashboard-row {
    margin-top: 16px;
  }
  
  .stats-section .el-row {
    margin-bottom: 0;
  }
  
  .stat-card {
    padding: 0 16px;
  }
  
  .stat-icon {
    width: 56px;
    height: 56px;
    font-size: 22px;
    margin-right: 14px;
  }
  
  .stat-value {
    font-size: 26px;
  }
  
  .monthly-stats-content {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 16px;
  }
  
  .monthly-item {
    width: calc(50% - 8px);
    justify-content: flex-start;
  }
  
  .orders-card {
    min-height: 420px;
  }
  
  .orders-list {
    max-height: calc(100vh - 500px);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .dashboard-content {
    padding: 12px;
  }
  
  .dashboard-row {
    margin-top: 12px;
  }
  
  .section-title {
    font-size: 18px;
    margin-bottom: 16px;
  }
  
  .section-title::before {
    width: 3px;
    height: 18px;
  }
  
  .stat-card-wrapper {
    margin-bottom: 12px;
    height: 190px; /* 减小高度 */
  }
  
  /* 重写 Element Plus 卡片内边距 */
  .stat-card-wrapper :deep(.el-card__body) {
    padding: 0 !important; /* 移除默认的 20px padding */
    height: 100%;
  }
  
  .stat-card {
    padding: 4px 8px; /* 恢复适当的内边距 */
    flex-direction: column;
    text-align: center;
    justify-content: center; /* 居中对齐 */
    gap: 3px; /* 减小元素间距 */
    height: 100%; /* 占满整个卡片高度 */
  }
  
  .stat-icon {
    width: 36px; /* 减小图标 */
    height: 36px;
    font-size: 16px;
    margin-right: 0;
    margin-bottom: 3px;
  }
  
  .stat-value {
    font-size: 18px; /* 减小数值字体 */
    font-weight: 700;
    line-height: 1;
    color: #333;
  }
  
  .stat-title {
    font-size: 11px; /* 减小标题字体 */
    margin-bottom: 2px;
    color: #666;
    font-weight: 500;
  }
  
  .monthly-stats-content {
    flex-direction: column;
    gap: 12px; /* 减小间距 */
    padding: 12px 0; /* 减小内边距 */
  }
  
  .monthly-item {
    width: 100%;
    justify-content: flex-start;
    padding: 4px 0; /* 减小内边距 */
  }
  
  .monthly-icon {
    width: 36px; /* 减小图标 */
    height: 36px;
    font-size: 16px;
    margin-right: 10px;
  }
  
  .monthly-label {
    font-size: 12px; /* 减小字体 */
    margin-bottom: 2px;
  }
  
  .monthly-value {
    font-size: 16px; /* 减小字体 */
    font-weight: 600;
  }
  
  .orders-card {
    min-height: 350px;
    margin-bottom: 16px;
  }
  
  .orders-list {
    max-height: 280px;
  }
  
  .empty-container {
    height: 250px;
  }
  
  .order-item,
  .active-order-item {
    padding: 12px;
    margin-bottom: 8px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    margin-bottom: 8px;
  }
  
  .order-number {
    font-size: 13px;
  }
  
  .order-amount {
    font-size: 15px;
  }
  
  .order-status {
    padding: 3px 8px;
    font-size: 11px;
  }
  
  .info-row {
    font-size: 13px;
    margin-bottom: 4px;
  }
  
  .info-row span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 200px;
  }
  
  .order-meta {
    flex-direction: column;
    gap: 2px;
    margin-bottom: 8px;
    font-size: 12px;
  }
  
  .order-actions {
    flex-direction: row;
    gap: 6px;
    justify-content: space-between;
  }
  
  .order-actions .el-button {
    flex: 1;
    font-size: 12px;
    padding: 6px 8px;
  }
  
  .empty-container {
    height: 200px;
  }
  
  .empty-container .el-empty {
    padding: 20px 0;
  }
  
  .card-header {
    font-size: 15px;
  }
  
  .card-header .el-button {
    font-size: 12px;
    padding: 6px 10px;
  }
  
  .priority-legend {
    gap: 8px;
    font-size: 11px;
  }
  
  .header-left {
    gap: 6px;
  }
  
  .priority-indicator {
    top: 6px;
    right: 6px;
  }
  
  .priority-dot {
    width: 10px;
    height: 10px;
  }
}

/* 小屏手机适配 */
@media (max-width: 480px) {
  .dashboard-content {
    padding: 8px;
  }
  
  .section-title {
    font-size: 16px;
    margin-bottom: 12px;
  }
  
  .stat-card-wrapper {
    height: 90px; /* 减小高度 */
    margin-bottom: 8px;
  }
  
  /* 重写 Element Plus 卡片内边距 */
  .stat-card-wrapper :deep(.el-card__body) {
    padding: 8px !important; /* 移除默认的 20px padding */
    height: 100%;
  }
  
  .stat-card {
    padding: 2px 6px; /* 适当的内边距 */
    gap: 2px; /* 减小元素间距 */
    justify-content: center; /* 居中对齐 */
    height: 100%; /* 占满整个卡片高度 */
  }
  
  .stat-icon {
    width: 32px; /* 减小图标大小 */
    height: 32px;
    font-size: 14px;
    margin-bottom: 2px;
  }
  
  .stat-value {
    font-size: 16px; /* 减小数值字体大小 */
    font-weight: 700;
    line-height: 1;
  }
  
  .stat-title {
    font-size: 10px; /* 减小标题字体大小 */
    color: #666;
    font-weight: 500;
  }
  
  .monthly-icon {
    width: 32px; /* 减小图标 */
    height: 32px;
    font-size: 14px;
  }
  
  .monthly-label {
    font-size: 11px; /* 减小字体 */
  }
  
  .monthly-value {
    font-size: 14px; /* 减小字体 */
    font-weight: 600;
  }
  
  .order-item,
  .active-order-item {
    padding: 10px;
  }
  
  .info-row span {
    max-width: 150px;
  }
  
  .order-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .order-actions .el-button {
    width: 100%;
    margin: 0;
  }
}

/* 超小屏适配 */
@media (max-width: 360px) {
  .stat-card {
    padding: 1px 4px; /* 适当的内边距 */
    gap: 1px;
    justify-content: center; /* 居中对齐 */
  }
  
  .stat-icon {
    width: 28px; /* 进一步减小图标大小 */
    height: 28px;
    font-size: 12px;
  }
  
  .stat-value {
    font-size: 14px; /* 减小数值字体 */
    font-weight: 700;
  }
  
  .stat-title {
    font-size: 9px; /* 减小标题字体 */
    font-weight: 500;
  }
  
  .order-item,
  .active-order-item {
    padding: 8px;
  }
  
  .info-row span {
    max-width: 120px;
  }
  
  .location-info {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .location-display {
    width: 100%;
  }
  
  .location-actions {
    width: 100%;
  }
  
  .location-actions .el-button {
    width: 100%;
  }
}

/* 订单详情弹框样式 */
.order-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-section h4::before {
  content: '';
  width: 3px;
  height: 16px;
  background: #409eff;
  border-radius: 2px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  padding: 8px 0;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-row .value {
  color: #333;
  flex: 1;
  text-align: right;
  word-break: break-all;
}

.detail-row .value.amount {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.detail-row .value.address {
  font-size: 14px;
  line-height: 1.4;
}

.detail-row .value.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.items-list {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
}

.item-row {
  padding: 6px 0;
  border-bottom: 1px solid #e9ecef;
  color: #333;
}

.item-row:last-child {
  border-bottom: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 移动端订单详情适配 */
@media (max-width: 768px) {
  .order-detail-content {
    max-height: 60vh;
  }
  
  .detail-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .detail-row .value {
    text-align: left;
  }
  
  .detail-section h4 {
    font-size: 15px;
  }
  
  .detail-row .label {
    min-width: auto;
    font-size: 14px;
  }
  
  .detail-row .value {
    font-size: 14px;
  }
}
</style>
